﻿namespace DotNetUtility.Parser
{
    using System;

    /// <summary>
    /// To parse an enum.
    /// </summary>
    public static class EnumParser
    {
        /// <summary>
        /// To Parse a string to relevent enum value.
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <param name="item"></param>
        /// <param name="ignorecase"></param>
        /// <returns>Matched Enum value or other wise default enum value.</returns>
        /// <example>
        ///     <code>
        ///         enum MyEnum
        ///         {
        ///             One=0,
        ///             Two
        ///         }
        ///         string stringToEnum ="One";
        ///         var parsedEnum = ParseEnum<MyEnum>(stringToEnum);
        ///     </code>
        /// </example>
        /// Contributed by Mohammad Rahman
        public static TEnum ParseEnum<TEnum>(string item, bool ignorecase = default(bool))
            where TEnum : struct
        {
            TEnum tenumResult = default(TEnum);
            return Enum.TryParse<TEnum>(item, ignorecase, out tenumResult) ?
                tenumResult : default(TEnum);
        }
    }
}
